<?php

class Medal_stock_issue_model extends CI_Model {

    function MedalStockIssueModel() {
        parent::Model();
    }

    function edit() {
        $return = array();
        if ($this->_checkExistingIssueNumber(check_post('issueid'))) {
            $return['result'] = false;
            $return['message'] = 'លេខចេញឃ្លាំងធ្លាប់មានរួចហើយ.';
            return $return;
        }
        $this->db->where('ID', check_post('issueid'));
        $this->db->update('Medal_Stock_Issue', array(
            'issue_number' => check_post('issuenumber'),
            'date' => $this->db->convertDate(check_post('issue-date')),
            'issue_for' => check_post('forperson'),
            'organization' => check_post('organization')
        ));
        $return['result'] = true;
        $return['message'] = 'កែប្រែព័ត៌មានចេញឃ្លាំងបានជោគជ័យ.';
        return $return;
    }

    function add() {
        $return = array();
        if ($this->_checkExistingIssueNumber()) {
            $return['result'] = false;
            $return['message'] = 'លេខចេញឃ្លាំងធ្លាប់មានរួចហើយ.';
            return $return;
        }
        if ($this->_checkExistingOfficialOrder()) {
            $return['result'] = false;
            $return['message'] = 'ក្រឹត្យនេះធ្លាប់បានចេញរួចហើយ.';
            return $return;
        }
            $this->db->insert('Medal_Stock_Issue', array(
                'issue_number' => check_post('issuenumber'),
                'date' => $this->db->convertDate(check_post('issue-date')),
                'issue_for' => check_post('forperson'),
                'organization' => check_post('organization')
            ));
            $this->_stock_issue($this->db->insert_id());
            $return['result'] = true;
            $return['message'] = 'បញ្ចេញឃ្លាំងបានជោគជ័យ';
        return $return;
    }

    function _checkExistingIssueNumber($id = null) {
        if (!empty($id)) {
            $query = $this->db->get_where('Medal_Stock_Issue', array('issue_number' => check_post('issuenumber'), "ID <> " => $id));
        } else {
            $query = $this->db->get_where('Medal_Stock_Issue', array('issue_number' => check_post('issuenumber')));
        }
        return $query->num_rows() > 0;
    }

    function _checkExistingOfficialOrder() {
        $officialOrders = $_POST['issue-official-order'];
        foreach ($officialOrders as $officialOrder) {
            $query = $this->db->get_where('Medalissue_Order', array('official_order_ID' => $officialOrder));
        }
        return $query->num_rows() > 0;
    }

    function getMedalID($typeID, $classID = null) {
        $this->db->select("ID");
        if (!empty($classID)) {
            $row = $this->db->get_where("Medal", array("Medal_Type_ID" => $typeID, "Medal_Class_ID" => $classID))->result_array();
        } else {
            $row = $this->db->get_where("Medal", array("Medal_Type_ID" => $typeID))->result_array();
        }
        return $row[0]['ID'];
    }

    function _stock_issue($issueId = null) {

        // Official Order already stock issue
        $officialOrders = $_POST['issue-official-order'];
        foreach ($officialOrders as $officialOrder) {
            $this->db->insert('Medalissue_Order', array(
                'medal_stock_issue_ID' => $issueId,
                'official_order_ID' => $officialOrder
            ));
        }

        // Stock issue
        $medals = $_POST['medal'];
        foreach ($medals as $typeId => $classes) {
            if (is_array($classes)) {
                foreach ($classes as $classId => $value) {
                    $medalID = $this->getMedalID($typeId, $classId);
                    // 
                    //  We won't cut stock when issued amount
                    // 
//                    $this->db->query("UPDATE Medal_Stock SET amount = amount - {$value} WHERE medal_ID = {$medalID}");
                    $this->db->insert('Medal_Stock_Issue_Amount', array(
                        'Medal_ID' => $medalID,
                        'Medal_Stock_Issue_ID' => $issueId,
                        'amount' => $value
                    ));
                }
            } else {
                $medalID = $this->getMedalID($typeId);
//                $this->db->query("UPDATE Medal_Stock SET amount = amount - {$classes} WHERE medal_ID = {$medalID}");
                $this->db->insert('Medal_Stock_Issue_Amount', array(
                    'Medal_ID' => $medalID,
                    'Medal_Stock_Issue_ID' => $issueId,
                    'amount' => $classes
                ));
            }
        }
    }

    function getStockIssue() {

        $aColumns = array('ID', 'issue_number', 'date');
        $where = "";

        if (isset($_GET['iSortCol_0'])) {
            for ($i = 0; $i < intval(check_get('iSortingCols')); $i++) {
                if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                    $this->db->order_by($aColumns[intval($_GET['iSortCol_' . $i])], $_GET['sSortDir_' . $i]);
                }
            }
        } else {
            $this->db->order_by("Medal_Stock_Issue.ID", "ASC");
        }
        $order = $this->db->ar_orderby;

        if (trim($_GET['sissuenumber']) != '' && !$this->db->is_contain($_GET['sissuenumber'], 'លេខ')) {
            $where .= $where != "" ? " AND " : " ";
            $where .= " issue_number LIKE '%" . check_get('sissuenumber') . "%' ";
        }
        if ($_GET['fromissuedate'] != '' && strpos($_GET['fromissuedate'], '/')) {
            $where .= $where != "" ? " AND " : " ";
            $where .= " date >= '" . $this->db->convertDate(check_get('fromissuedate')) . "'";
        }
        if ($_GET['toissuedate'] != '' && strpos($_GET['toissuedate'], '/')) {
            $where .= $where != "" ? " AND " : " ";
            $where .= " date <= '" . $this->db->convertDate(check_get('toissuedate')) . "'";
        }
        if ($where != "") {
            $this->db->where($where);
        }

        $this->db->select('Medal_Stock_Issue.ID');

        $totalQuery = $this->db->get('Medal_Stock_Issue');
        if ($where != "") {
            $this->db->where($where);
        }

        $this->db->select('Medal_Stock_Issue.ID, Medal_Stock_Issue.issue_number, Medal_Stock_Issue.date');
        $query = $this->db->get('Medal_Stock_Issue', check_get('iDisplayStart'), check_get('iDisplayLength'), $order);
        $stock_issues = $query->result_array();
        $aaData = array();
        $i = check_get('iDisplayStart');
        foreach ($stock_issues as $stock_issue) {
            $data = array(++$i, $stock_issue['issue_number'], date("d/m/Y", strtotime($stock_issue['date'])), "<a class='edit-btn edit-issue' title='កែប្រែ' rel='{$stock_issue['ID']}'>&nbsp;</a>");
            array_push($aaData, $data);
        }


        $output = array(
            "sEcho" => intval(!empty($_GET['sEcho']) ? $_GET['sEcho'] : ""),
            "iTotalRecords" => $query->num_rows(),
            "iTotalDisplayRecords" => $totalQuery->num_rows(),
            "aaData" => $aaData
        );
        return $output;
    }

    public

    function getNewIssue() {
        $aColumns = array('ID', 'issue_number', 'date');
        $where = "";
        if (isset($_GET['iSortCol_0'])) {
            for ($i = 0; $i < intval(check_get('iSortingCols')); $i++) {
                if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                    $this->db->order_by($aColumns[intval($_GET['iSortCol_' . $i])], $_GET['sSortDir_' . $i]);
                }
            }
        } else {
            $this->db->order_by("Medal_Stock_Issue.ID", "ASC");
        }
        $order = $this->db->ar_orderby;
        $this->db->select('Medal_Stock_Issue.ID');
        $totalQuery = $this->db->get('Medal_Stock_Issue');
        $this->db->select('Medal_Stock_Issue.ID, Medal_Stock_Issue.issue_number, Medal_Stock_Issue.date');
        $query = $this->db->get('Medal_Stock_Issue', check_get('iDisplayStart'), check_get('iDisplayLength'), $order);
        $stock_issues = $query->result_array();
        $aaData = array();
        $i = check_get('iDisplayStart');
        foreach ($stock_issues as $stock_issue) {
            $data = array(++$i, $stock_issue['issue_number'], date("d/m/Y", strtotime($stock_issue['date'])));
            array_push($aaData, $data);
        }
        $output = array(
            "sEcho" => intval(!empty($_GET['sEcho']) ? $_GET['sEcho'] : ""),
            "iTotalRecords" => $query->num_rows(),
            "iTotalDisplayRecords" => $totalQuery->num_rows(),
            "aaData" => $aaData
        );
        return $output;
    }

}

?>